package com.alone.wchat.admin.system.service.impl;


import com.alone.wchat.admin.system.entity.SysMenuEntity;
import com.alone.wchat.admin.system.entity.SysUserEntity;
import com.alone.wchat.admin.system.entity.SysUserTokenEntity;
import com.alone.wchat.admin.system.mapper.SysUserMapper;
import com.alone.wchat.admin.system.service.IShiroService;
import com.alone.wchat.admin.system.service.ISysUserTokenService;
import com.alone.wchat.admin.system.service.SysMenuService;
import com.alone.wchat.admin.system.service.SysUserService;
import com.alone.wchat.common.utils.Constant;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements IShiroService {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private ISysUserTokenService sysUserTokenService;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            EntityWrapper<SysMenuEntity> ew=new EntityWrapper<>();
            List<SysMenuEntity> menuList = sysMenuService.selectList(ew);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = userMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public SysUserTokenEntity queryByToken(String accessToken) {
        SysUserTokenEntity sysUserToken=new SysUserTokenEntity();
        sysUserToken.setToken(accessToken);
        EntityWrapper<SysUserTokenEntity> ew=new EntityWrapper<>();
        ew.eq("token",accessToken);
        return sysUserTokenService.selectOne(ew);
    }

    @Override
    public SysUserEntity queryUser(Long userId) {
        return userService.selectById(userId);
    }

}
